package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.utils.DateTimeZoneConverter;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.dto.*;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.service.IDeviceDataService;
import com.zzyl.nursing.service.IDeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 设备数据Service业务层处理
 *
 * @author ruoyi
 * @date 2025-08-03
 */
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService {
    @Autowired
    private DeviceDataMapper deviceDataMapper;

    @Autowired
    private IDeviceService deviceService;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 查询设备数据
     *
     * @param id 设备数据主键
     * @return 设备数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id) {
        return getById(id);
    }

    /**
     * 查询设备数据列表
     *
     * @param deviceData 设备数据
     * @return 设备数据
     */
    @Override
    public List<DeviceData> selectDeviceDataList(DeviceData deviceData) {
        return deviceDataMapper.selectDeviceDataList(deviceData);
    }

    /**
     * 新增设备数据
     *
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData) {
        return save(deviceData) ? 1 : 0;
    }

    /**
     * 修改设备数据
     *
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData) {
        return updateById(deviceData) ? 1 : 0;
    }

    /**
     * 批量删除设备数据
     *
     * @param ids 需要删除的设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备数据信息
     *
     * @param id 设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id) {
        return removeById(id) ? 1 : 0;
    }


    /**
     * 批量保存数据
     *
     * @param iotMsgNotifyData
     */
    public void batchInsertDeviceData(IotMsgNotifyData iotMsgNotifyData) {

        String deviceId = iotMsgNotifyData.getHeader().getDeviceId();

        Device device = deviceService.getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, deviceId));
//        Device device = deviceMapper.selectOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, deviceId));
        if (ObjectUtil.isEmpty(device)) {
            System.out.println("设备不存在");
            return;
        }

        //取数据
        List<IotMsgService> services = iotMsgNotifyData.getBody().getServices();
        services.forEach(service -> {
            Map<String, Object> properties = service.getProperties();
            //如果有一个是空，直接return
            if (MapUtil.isEmpty(properties)) {
                return;
            }

            //处理上报时间

            String eventTimeStr = service.getEventTime();
            LocalDateTime localDateTime = LocalDateTimeUtil.parse(eventTimeStr, "yyyyMMdd'T'HHmmss'Z'");
            LocalDateTime eventTime = DateTimeZoneConverter.utcToShanghai(localDateTime);

            List<DeviceData> deviceDataList = new ArrayList<>();//批量保存的数据
            properties.forEach((key, value) -> {
                        DeviceData deviceData = BeanUtil.toBean(device, DeviceData.class);
                        deviceData.setId(null);
                        //接入位置
                        deviceData.setAccessLocation(device.getBindingLocation());
                        //时间
                        deviceData.setAlarmTime(eventTime);
                        deviceData.setFunctionId(key);
                        deviceData.setDataValue(value + "");
                        deviceData.setCreateBy(null);
                        deviceData.setUpdateBy(null);
                        deviceData.setCreateTime(null);
                        deviceData.setUpdateTime(null);
                        deviceDataList.add(deviceData);
                    }
            );

            this.saveBatch(deviceDataList);


            // 存入到redis  key：hash数据类型（大key，小key,  value）iot:device_last_data   iot_id
            redisTemplate.opsForHash().put(CacheConstants.IOT_DEVICE_LAST_DATA, device.getIotId(), JSONUtil.toJsonStr(deviceDataList));
        });

    }

    /**
     * 查询健康数据（查询Redis中的数据）
     *
     * @param deviceDto
     * @return
     */
    @Override
    public Map<String, HealthDataDto> selectHealthData(DeviceDto deviceDto) {
        //1. 根据设备名称和产品名称查询设备
        Device device1 = deviceService.getOne(Wrappers.<Device>lambdaQuery()
                .eq(Device::getDeviceName, deviceDto.getDeviceName())
                .eq(Device::getProductKey, deviceDto.getProductKey()));
        //2. 根据设备iot查询Redis中（实时更新）的设备数据
        String deviceDataStr = (String) redisTemplate.opsForHash().get(CacheConstants.IOT_DEVICE_LAST_DATA, device1.getIotId());
        //3. 解析设备数据
        List<DeviceData> deviceDataList = JSONUtil.toList(JSONUtil.parseArray(deviceDataStr), DeviceData.class);

        HealthDataDto healthDataDto = new HealthDataDto();// 转换成健康数据，用于响应前端页面
        DeviceDataDto deviceDataDto = new DeviceDataDto();// 设备数据转换成设备数据Dto

        List<DeviceDataDto> propertyStatusInfo = new ArrayList<>();// 设备数据Dto

        //4. 遍历从Redis中获取的设备数据
        deviceDataList.forEach(deviceData -> {

            deviceDataDto.setIdentifier(deviceData.getFunctionId());
//            deviceDataDto.setTime(String.valueOf(deviceData.getAlarmTime()));
            //转成时间戳
            deviceDataDto.setTime(String.valueOf(deviceData.getAlarmTime().atZone(ZoneId.of("Asia/Shanghai")).toInstant().toEpochMilli()));
            deviceDataDto.setIdentifier(deviceData.getFunctionId());
            deviceDataDto.setValue(deviceData.getDataValue());
            propertyStatusInfo.add(deviceDataDto);

        });
        //5. 封装最后的响应数据
        Map<String, HealthDataDto> list = new HashMap<>();
        healthDataDto.setPropertyStatusInfo(propertyStatusInfo);
        list.put("list", healthDataDto);
        //返回list集合
        return list;
    }

    /**
     * 按天统计查询指标数据
     *
     * @param queryDeviceDataByDayDto 查询参数
     * @return
     */
    @Override
    public List<Map<String, Object>> queryDeviceDataListByDay(QueryDeviceDataByDayDto queryDeviceDataByDayDto) {


        //1. 查询设备数据
        List<DeviceData> deviceDataList = getDeviceData(queryDeviceDataByDayDto);
        //2. 封装数据  一个map用来封装数据，另一个map计数
        TreeMap<String, Double> map = new TreeMap<>();
        Map<String, Integer> countMap = new HashMap<>();
        List<Map<String, Object>> list = new ArrayList<>();
        for (int i = 0; i < 24; i++) {
            if (i < 10){
                map.put("0" + i + ":00", 0.0);

                countMap.put("0" + i + ":00", 0);

            }else {
                map.put(i + ":00", 0.0);
                countMap.put(i + ":00", 0);
            }
        }

        //3. 遍历查找到的设备数据列表 ， 用来累加每个时间段的值
        deviceDataList.forEach(deviceData -> {
            String time = deviceData.getAlarmTime().format(DateTimeFormatter.ofPattern("HH:00"));
            map.put(time, map.get(time) + Double.parseDouble(deviceData.getDataValue()));
            countMap.put(time, countMap.get(time) + 1);
        });
        //4. 计算平均值,并封装成最后返回的响应数据
        map.forEach((key, value) -> {
            Double avg=0.0;
            if (countMap.get(key) != 0){
                 avg =value / countMap.get(key);
            }
                HashMap<String, Object> mapParam = new HashMap<>();
                //格式化avg
                mapParam.put("dateTime",key);
                mapParam.put("dataValue", Double.valueOf(new DecimalFormat("0.0").format(avg)));
                list.add(mapParam);

        });

        return list;

    }

    /**
     * 按周统计查询指标数据
     *
     * @param queryDeviceDataByDayDto 查询参数
     * @return
     */
    @Override
    public List<Map<String, Object>> queryDeviceDataListByWeek(QueryDeviceDataByDayDto queryDeviceDataByDayDto) {
        //用来存储最后响应的list集合
        List<Map<String, Object>> list = new ArrayList<>();

        //1. 先获取开始时间和结束时间，用来封装最近一周的日期
        LocalDateTime startTime = LocalDateTimeUtil.of(Long.valueOf(queryDeviceDataByDayDto.getStartTime()));//获取当前时间对应的LocalDateTime对象
        LocalDateTime endTime = LocalDateTimeUtil.of(Long.valueOf(queryDeviceDataByDayDto.getEndTime()));
        //2. 获取设备数据
        List<DeviceData> deviceDataList = getDeviceData(queryDeviceDataByDayDto);


        //3. 把最近的日期封装到TreeMap中，对应的值设置为0.0，countMap也初始化为0
        TreeMap<String, Double> map = new TreeMap<>();
        Map<String, Integer> countMap = new HashMap<>();
        for (LocalDateTime date =startTime; date.isBefore(endTime); date = date.plusDays(1)) {
            String format = LocalDateTimeUtil.format(date, "MM-dd");
            map.put(format, 0.0);
            countMap.put(format, 0);
        }

        //4. 遍历设备数据，把数据累加到map中
        deviceDataList.forEach(deviceData -> {
            LocalDateTime time = deviceData.getAlarmTime();
            String timeStr =LocalDateTimeUtil.format(time, "MM-dd");//格式化时间
            map.put(timeStr, map.get(timeStr) + Double.parseDouble(deviceData.getDataValue()));
            countMap.put(timeStr, countMap.get(timeStr) + 1);
        });

        //5. 遍历map，把数据平均值封装成响应数据
        map.forEach((key, value) -> {
            Double avg=0.0;
            if (countMap.get(key) != 0.0){
                avg =value / countMap.get(key);
            }
            HashMap<String, Object> mapParam = new HashMap<>();
            //把key转成 获取开始的月和日  格式：08.07
            String[] split = key.split("-");
                mapParam.put("dateTime",split[0] + "." + split[1]);
                mapParam.put("dataValue", avg.intValue());
            list.add(mapParam);
        });



        return list;
    }

    private List<DeviceData> getDeviceData(QueryDeviceDataByDayDto queryDeviceDataByDayDto) {
        LocalDateTime startTime = LocalDateTimeUtil.of(Long.valueOf(queryDeviceDataByDayDto.getStartTime()));//获取当前时间对应的LocalDateTime对象
        LocalDateTime endTime = LocalDateTimeUtil.of(Long.valueOf(queryDeviceDataByDayDto.getEndTime()));
        String startTimeStr= LocalDateTimeUtil.format(startTime, "yyyy-MM-dd HH:mm:ss");
        String endTimeStr= LocalDateTimeUtil.format(endTime, "yyyy-MM-dd HH:mm:ss");


        queryDeviceDataByDayDto.setStartTime(startTimeStr);
        queryDeviceDataByDayDto.setEndTime(endTimeStr);


        //1. 根据iod和functionId查询设备的属性数据
        List<DeviceData> deviceDataList = this.list(Wrappers.<DeviceData>lambdaQuery()

                .eq(DeviceData::getIotId, queryDeviceDataByDayDto.getIotId())
                .eq(DeviceData::getFunctionId, queryDeviceDataByDayDto.getFunctionId())
                .between(DeviceData::getAlarmTime, queryDeviceDataByDayDto.getStartTime(), queryDeviceDataByDayDto.getEndTime()));
        return deviceDataList;
    }

}
